from fastapi import FastAPI, APIRouter, Depends
from pydantic import BaseModel
from typing import List
from loguru import logger
from ..utils.db import MongoDBManager

# 全局变量
_queue = None
_shared_list = None

class UrlRequest(BaseModel):
    urls: List[str]

class ApiResponse(BaseModel):
    message: str
    code: int

def init_router_dependencies(q, shared_list):
    """初始化路由依赖的全局变量"""
    global _queue, _shared_list
    _queue = q
    _shared_list = shared_list

def get_queue():
    return _queue

def get_shared_list():
    return _shared_list

def get_db():
    db = MongoDBManager()
    try:
        yield db
    finally:
        db.close()

router = APIRouter()

@router.get("/get_waiting_count/")
async def get_waiting_count(q=Depends(get_queue)):
    return {'count': q.qsize()}

@router.get("/get_black_urls/")
async def get_black_urls(db: MongoDBManager = Depends(get_db)):
    black_lst = db.get_db_black_urls()
    return black_lst

@router.get("/get_shared_list/")
async def get_shared_list(shared_list=Depends(get_shared_list)):
    return {'shared_list': shared_list[:]}

@router.get("/get_shared_count/")
async def get_shared_count(shared_list=Depends(get_shared_list)):
    return {'shared_count': len(shared_list)}

@router.post("/add_url/")
async def add_live_room_forever_url(
    request: UrlRequest,
    q=Depends(get_queue),
    shared_list=Depends(get_shared_list),
    db: MongoDBManager = Depends(get_db)
):
    """
    添加直播间URL
    """
    logger.debug('add_url 收到请求')
    black_urls = db.get_db_black_urls()
    logger.debug('black_urls 查询完毕')
    
    url_list = []
    queue_list = []

    # 获取当前队列中的所有URL
    while not q.empty():
        item = q.get()
        queue_list.append(item)

    # 将URL放回队列
    for queue_url in queue_list:
        q.put(queue_url)

    # 处理新的URL
    for url in request.urls:
        if url in shared_list:
            continue
        if url in black_urls:
            continue
        if url in queue_list:
            continue
        url_list.append(url)
        q.put(url)

    if url_list:
        db.insert_db_urls(url_list)
        logger.debug('insert_db_urls 插入完毕')
        return ApiResponse(
            message=f"{url_list} 添加成功 总共添加数量 {len(url_list)}",
            code=200
        )
    else:
        return ApiResponse(
            message="提供链接均已经存在",
            code=400
        ) 